<?php
// +----------------------------------------------------------------------
// | [KyPHP System] Copyright (c) 2020 http://www.kuryun.com/
// +----------------------------------------------------------------------
// | [KyPHP] 并不是自由软件,你可免费使用,未经许可不能去掉KyPHP相关版权
// +----------------------------------------------------------------------
// | Author: fudaoji <fdj@kuryun.cn>
// +----------------------------------------------------------------------
/**
 * Created by PhpStorm.
 * Script Name: AddonMp.php
 * Create: 2020/6/29 15:50
 * Description: 公众号应用公共手机网页控制器
 * Author: fudaoji<fdj@kuryun.cn>
 */
namespace app\common\controller;

use ky\SaveParam;

class AddonMp extends Addon
{
    //protected $openPlatform;
    protected $mpApp;
    protected $mpInfo;
    /**
     * @var \think\Model
     */
    protected $mpM;
    protected $followInfo;
    /**
     * 是否需要微信网页授权，各应用可以设置此参数控制应用中的网页是否需要发起微信网页授权
     * @var bool
     */
    protected $needWxLogin = true;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->mpM = model('common/mp');
        $this->setMpInfo();
        $this->setApp();
        $this->setFollowInfo();
    }

    /**
     * 设置微信公众号信息
     * @author fudaoji<fdj@kuryun.cn>
     */
    protected function setMpInfo() {
        if($this->mid){
            $this->mpInfo = $this->mpM->getOne($this->mid);
            if(empty($this->mpInfo)){
                echo("公众号不存在");exit;
            }
        }
        $this->assign('mp_info', $this->mpInfo);
    }

    /**
     * 设置授权公众号应用
     * @author fudaoji<fdj@kuryun.cn>
     */
    protected function setApp() {
        if($this->mpInfo) {
            $this->mpApp = controller('mp/mp', 'event')->getApp($this->mpInfo);
            $this->assign('mp_app', $this->mpApp);
        }
        //$this->openPlatform = controller('mp', 'event')->getOpenPlatform();
    }

    /**
     * 设置微信用户信息
     * @author: fudaoji<fdj@kuryun.cn>
     */
    protected function setFollowInfo(){
        if($this->needWxLogin){
            if (empty(cookie('weixin_user'))) {
                // 未授权登录
                cookie('target_url' , request()->domain().request()->url());
                //发起授权
                $this->mpApp->oauth->scopes(['snsapi_userinfo'])
                    ->redirect(request()->domain() . url('mp/Onmessage/wxAuthCallback', ['mid' => $this->mid]))->send();exit;
            }
            $this->followInfo = json_decode(SaveParam::authCode(cookie('weixin_user')), true);
            cookie('weixin_user', SaveParam::authCode(json_encode($this->followInfo), 'ENCODE'), 604800); //保存用户信息
            $this->assign('follow_info', $this->followInfo);
        }
    }
}